<template>
  <div class="acceleration-chart">
    <div class="chart-title">
      <div class="title-left">
        <span>{{currentDevice.latheName}}加速度数据</span>
        <!-- 状态标签 -->
        <div class="status-indicator" :class="getStatusClass(getLatheNameStatusLocal(currentDevice.latheName))">
          {{ getLatheNameStatusLocal(currentDevice.latheName) }}
        </div>
      </div>
      <div class="title-right">
        <!-- 安装位置下拉选择器 - 仅在设备有数据且有位置信息时显示 -->
        <div class="position-dropdown" v-if="hasDeviceData(currentDevice.id) && devicePositions.length > 0">
          <el-dropdown trigger="click" @command="switchPosition">
            <span class="el-dropdown-link">
              {{ currentPosition || '选择位置' }}
              <i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                v-for="(position, index) in devicePositions"
                :key="'pos-'+index"
                :command="position"
                :class="{ 'is-active': currentPosition === position }">
                {{ position }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>

        <!-- 类型切换按钮组 - 始终显示 -->
        <div class="acceleration-type-selector">
          <button class="type-btn" :class="{ active: accelerationType === 'rms' }"
                  @click="switchAccelerationType('rms')">
            均方根
          </button>
          <button class="type-btn" :class="{ active: accelerationType === 'peak' }"
                  @click="switchAccelerationType('peak')">
            峰值
          </button>
        </div>
        <!-- 一键问询按钮 -->
        <button class="ai-btn" @click="goToInquiry" :disabled="!currentDevice.id">
          <i class="el-icon-chat-dot-round"></i>
          问询AI
        </button>
      </div>
    </div>
    <div class="chart-container">
      <div id="accelerationChart" style="height: 100%; width: 100%;"></div>

      <!-- 设备状态遮罩 - 当设备处于非正常状态时显示 -->
      <div v-if="shouldShowStatusMask" class="status-mask">
        <div class="mask-content">
          <div class="status-icon">
            <i :class="getStatusIcon(getLatheNameStatusLocal(currentDevice.latheName))"></i>
          </div>
          <div class="status-text">
            <h3>该设备处于【{{ getLatheNameStatusLocal(currentDevice.latheName) }}】状态</h3>
            <p>{{ getStatusMessage(getLatheNameStatusLocal(currentDevice.latheName)) }}</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import ChartDataManager from '@/utils/chartDataManager'

export default {
  name: 'AccelerationChart',
  props: {
    currentDevice: {
      type: Object,
      required: true
    },
    devicePositions: {
      type: Array,
      default: () => []
    },
    currentPosition: {
      type: String,
      default: ''
    },
    accelerationType: {
      type: String,
      default: 'rms'
    },
    deviceAccelerationData: {
      type: Object,
      default: () => ({})
    },
    getLatheNameStatus: {
      type: Function,
      required: true
    }
  },
  data() {
    return {
      accelerationChart: null,
      chartDataManager: null,
      isInitialized: false,
      lastUpdateTime: null,
      animationDuration: 300,
      updateAnimationId: null,
      xAxisLabelInterval: 3, // X轴标签显示间隔，每3个点显示一个（显示20个标签）
      cachedYAxisRange: { min: 0, max: 10 }, // 缓存的Y轴范围，避免频繁变化
      yAxisRangeUpdateThreshold: 5000 // Y轴范围更新阈值（毫秒）
    }
  },
  mounted() {
    // 初始化图表
    this.$nextTick(() => {
      this.initAccelerationChart();
    });

    // 监听窗口大小变化
    window.addEventListener('resize', this.handleResize);

    // 监听数据更新事件
    if (this.$bus) {
      this.$bus.$on('accelerationDataUpdate', this.handleWebSocketDataUpdate);
      this.$bus.$on('chartDataUpdate', this.handleChartDataUpdate);
      console.log('✅ AccelerationChart: 已注册数据监听器');
    } else {
      console.warn('⚠️ AccelerationChart: 事件总线未找到');
    }
  },
  beforeDestroy() {
    if (this.accelerationChart) {
      this.accelerationChart.dispose();
      this.accelerationChart = null;
    }
    window.removeEventListener('resize', this.handleResize);

    // 移除WebSocket事件监听
    if (this.$bus) {
      this.$bus.$off('accelerationDataUpdate', this.handleWebSocketDataUpdate);
      this.$bus.$off('windowDataUpdate', this.handleWindowDataUpdate);
    }
  },
  watch: {
    'currentDevice.id': {
      handler(newId, oldId) {
        if (newId !== oldId) {
          this.$nextTick(() => {
            if (this.hasDeviceData(newId)) {
              this.initAccelerationChart();
            }
          });
        }
      }
    },
    accelerationType: {
      handler(newType, oldType) {
        if (newType !== oldType) {
          this.$nextTick(() => {
            if (this.hasDeviceData(this.currentDevice.id)) {
              this.scheduleChartUpdate(); // 使用更轻量的更新而非重新初始化
            }
          });
        }
      }
    },
    // 优化：仅监听当前设备的数据变化，避免深度监听所有设备
    'deviceAccelerationData': {
      handler(newData, oldData) {
        const currentDeviceId = this.currentDevice.id;
        const newDeviceData = newData[currentDeviceId];
        const oldDeviceData = oldData ? oldData[currentDeviceId] : null;

        // 仅当当前设备数据发生变化时才更新
        if (newDeviceData !== oldDeviceData && this.hasDeviceData(currentDeviceId)) {
          this.scheduleChartUpdate();
        }
      },
      deep: false // 关闭深度监听，减少性能开销
    },
    currentPosition: {
      handler(newPos, oldPos) {
        if (newPos !== oldPos) {
          this.$nextTick(() => {
            if (this.hasDeviceData(this.currentDevice.id)) {
              this.scheduleChartUpdate();
            }
          });
        }
      }
    }
  },
  computed: {
    // 判断是否应该显示状态遮罩
    shouldShowStatusMask() {
      const status = this.getLatheNameStatusLocal(this.currentDevice.latheName);
      // 当设备处于非正常状态时显示遮罩
      return status !== '正常';
    }
  },
  methods: {
    /**
     * 初始化图表数据管理器
     */
    initializeChartDataManager() {
      this.chartDataManager = new ChartDataManager({
        windowSize: 600, // 10分钟窗口，假设1秒一个点
        timeWindow: 10 * 60 * 1000, // 10分钟
        updateThrottle: 100 // 100ms节流
      });

      // 设置更新回调
      this.chartDataManager.setUpdateCallback((deviceIds) => {
        if (deviceIds.includes(this.currentDevice.id)) {
          this.scheduleChartUpdate();
        }
      });

      console.log('📊 图表数据管理器已初始化');
    },



    hasDeviceData(deviceId) {
      if (this.chartDataManager) {
        const status = this.chartDataManager.getBufferStatus(deviceId);
        return status && status.dataCount > 0;
      }

      // 兼容旧的数据结构
      const deviceData = this.deviceAccelerationData[deviceId];
      return deviceData &&
             deviceData.timeData &&
             deviceData.rms &&
             deviceData.peak;
    },

    getLatheNameStatusLocal(latheName) {
      // 使用传入的 prop 函数
      return this.getLatheNameStatus(latheName);
    },

    // 获取状态对应的图标
    getStatusIcon(status) {
      const iconMap = {
        '正常': 'el-icon-success',
        '故障': 'el-icon-warning',
        '待机': 'el-icon-time',
        '离线': 'el-icon-error'
      };
      return iconMap[status] || 'el-icon-error';
    },

    // 获取状态对应的消息
    getStatusMessage(status) {
      const messageMap = {
        '正常': '设备运行正常，数据实时更新中',
        '故障': '设备检测到异常，暂无数据',
        '待机': '设备处于待机模式，暂无数据',
        '离线': '设备连接断开，暂无数据'
      };
      return messageMap[status] || '设备状态异常，暂无数据';
    },

    getStatusClass(status) {
      const statusMap = {
        '正常': 'normal',
        '故障': 'warning',
        '待机': 'waiting',
        '离线': 'offline'
      };
      return statusMap[status] || 'offline';
    },

    switchPosition(position) {
      this.$emit('switch-position', position);
    },

    switchAccelerationType(type) {
      this.$emit('switch-acceleration-type', type);
    },

    goToInquiry() {
      this.$emit('go-to-inquiry');
    },

    initAccelerationChart() {
      const chartContainer = document.getElementById('accelerationChart');
      if (!chartContainer) {
        console.warn('图表容器未找到');
        return;
      }

      if (!this.accelerationChart || this.accelerationChart.isDisposed()) {
        this.accelerationChart = echarts.init(chartContainer);
      }

      const option = this.getAccelerationChartOption();
      this.accelerationChart.setOption(option, true);
      this.accelerationChart.resize();

      console.log(`📊 图表已初始化，设备ID: ${this.currentDevice.id}`);
    },

    getAccelerationChartOption() {
      // 优先使用父组件的getAccelerationChartOption方法（参考index_before.vue实现）
      if (this.$parent && this.$parent.getAccelerationChartOption) {
        console.log('📊 使用父组件的getAccelerationChartOption方法');
        return this.$parent.getAccelerationChartOption();
      }

      // 备用方案：使用本组件的图表配置生成逻辑
      const deviceId = this.currentDevice.id;
      let displayData;

      // 优先使用父组件的数据管理器
      if (this.$parent && this.$parent.chartDataManager) {
        displayData = this.$parent.chartDataManager.getDisplayData(deviceId, this.accelerationType);
        console.log('📊 使用新数据管理器获取显示数据:', displayData.metadata);
      } else {
        // 兼容旧的数据结构
        displayData = this.getLegacyDisplayData(deviceId);
        console.log('📊 使用旧数据结构获取显示数据');
      }

      return this.buildChartOption(displayData.timeData, displayData.valueData);
    },

    /**
     * 获取兼容的显示数据
     */
    getLegacyDisplayData(deviceId) {
      const deviceData = this.deviceAccelerationData[deviceId];

      if (!deviceData) {
        return this.getEmptyDisplayData();
      }

      const currentData = this.accelerationType === 'rms' ? deviceData.rms : deviceData.peak;
      return {
        timeData: deviceData.timeData || [],
        valueData: currentData || { x: [], y: [], z: [] }
      };
    },


    buildChartOption(timeData, valueData) {
      // 过滤有效的时间数据，移除空值和null
      const filteredData = this.filterValidTimeData(timeData, valueData);

      // 去重时间标签，确保相邻标签不重复
      const deduplicatedTimeData = this.deduplicateTimeLabels(filteredData.timeData);
      filteredData.timeData = deduplicatedTimeData;

      // 动态计算图表边距、X轴间隔和Y轴范围
      const gridMargins = this.calculateGridMargins(filteredData.valueData);
      this.xAxisLabelInterval = this.calculateSmartXAxisInterval(filteredData.timeData);
      const yAxisRange = this.calculateStableYAxisRange(filteredData.valueData);

      return {
        backgroundColor: 'transparent',
        animation: true,
        animationDuration: 300,
        animationEasing: 'cubicOut',
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(0, 0, 0, 0.8)',
          borderColor: '#1890ff',
          borderWidth: 1,
          textStyle: { color: '#fff' },
          formatter: function(params) {
            if (!params || params.length === 0) return '';
            const timeIndex = params[0].dataIndex;
            const timeLabel = timeData[timeIndex] || '';
            let result = `时间: ${timeLabel}<br/>`;
            params.forEach(param => {
              const value = param.value !== null ? param.value.toFixed(3) : 'N/A';
              result += `${param.seriesName}: ${value} m/s²<br/>`;
            });
            return result;
          }
        },
        legend: {
          data: ['X轴', 'Y轴', 'Z轴'],
          textStyle: {
            color: '#fff',
            fontSize: 12
          },
          top: 5,
          left: 'center',
          itemGap: 20, // 增加图例项之间的间距
          itemWidth: 20, // 图例标记的宽度
          itemHeight: 12 // 图例标记的高度
        },
        grid: gridMargins,
        xAxis: {
          type: 'category',
          data: filteredData.timeData,
          boundaryGap: false, // 取消边界间隙，让数据贴边显示
          axisLabel: {
            color: '#fff',
            fontSize: 10,
            interval: (index, value) => {
              // 确保第一个标签总是显示，但不显示最后一个标签
              if (index === 0) {
                return true;
              }

              // 不显示最后一个标签（最新时间）
              if (index === filteredData.timeData.length - 1) {
                return false;
              }

              // 智能间隔：避免显示重复的时间标签
              if (index % this.xAxisLabelInterval === 0) {
                // 检查当前标签是否与前一个显示的标签相同
                const currentLabel = value;
                const prevDisplayIndex = Math.max(0, index - this.xAxisLabelInterval);
                const prevLabel = filteredData.timeData[prevDisplayIndex];

                // 如果标签相同，跳过显示
                if (currentLabel === prevLabel) {
                  return false;
                }

                return true;
              }

              return false;
            },
            rotate: 0, // 保持水平显示
            margin: 8, // 增加标签与轴线的距离
            formatter: function(value) {
              // 显示完整的时:分:秒格式
              return value || '';
            }
          },
          axisLine: {
            show: true,
            lineStyle: { color: 'rgba(255,255,255,0.5)' }
          },
          axisTick: {
            show: true,
            lineStyle: { color: 'rgba(255,255,255,0.5)' },
            interval: (index, value) => {
              // 确保第一个刻度总是显示，但不显示最后一个刻度
              if (index === 0) {
                return true;
              }

              // 不显示最后一个刻度
              if (index === filteredData.timeData.length - 1) {
                return false;
              }

              // 与标签显示保持一致的间隔策略
              if (index % this.xAxisLabelInterval === 0) {
                const currentLabel = filteredData.timeData[index];
                const prevDisplayIndex = Math.max(0, index - this.xAxisLabelInterval);
                const prevLabel = filteredData.timeData[prevDisplayIndex];

                // 如果标签相同，跳过显示刻度
                if (currentLabel === prevLabel) {
                  return false;
                }

                return true;
              }

              return false;
            }
          },
          splitLine: {
            show: false // 隐藏X轴的分割线，避免视觉混乱
          }
        },
        yAxis: {
          type: 'value',
          name: this.accelerationType === 'rms' ? 'RMS(m/s²)' : 'PEAK(m/s²)',
          nameTextStyle: {
            color: '#fff',
            fontSize: 12,
            padding: [0, 0, 0, 20] // 为Y轴标题添加内边距
          },
          axisLabel: {
            color: '#fff',
            fontSize: 11,
            margin: 8, // 增加标签与轴线的距离
            formatter: function(value) {
              // 格式化Y轴标签，避免过长
              if (value >= 1000) {
                return (value / 1000).toFixed(1) + 'k';
              }
              // 显示整数，避免小数点
              return Number.isInteger(value) ? value.toString() : value.toFixed(1);
            }
          },
          axisLine: {
            show: true,
            lineStyle: { color: 'rgba(255,255,255,0.5)' }
          },
          axisTick: {
            show: true,
            lineStyle: { color: 'rgba(255,255,255,0.5)' }
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(255,255,255,0.2)',
              type: 'dashed',
              width: 1
            }
          },
          // 使用计算出的稳定Y轴范围
          scale: false, // 禁用自动缩放
          min: yAxisRange.min, // 使用计算的最小值（通常为0）
          max: yAxisRange.max, // 使用计算的稳定最大值
          interval: this.calculateYAxisInterval(yAxisRange.min, yAxisRange.max) // 使用计算的刻度间隔
        },
        series: [
          {
            name: 'X轴',
            type: 'line',
            data: filteredData.valueData.x || [],
            smooth: 0.3,
            symbol: 'none',
            lineStyle: { color: '#ff6b6b', width: 2 },
            areaStyle: {
              color: {
                type: 'linear', x: 0, y: 0, x2: 0, y2: 1,
                colorStops: [
                  { offset: 0, color: 'rgba(255, 107, 107, 0.3)' },
                  { offset: 1, color: 'rgba(255, 107, 107, 0.05)' }
                ]
              }
            }
          },
          {
            name: 'Y轴',
            type: 'line',
            data: filteredData.valueData.y || [],
            smooth: 0.3,
            symbol: 'none',
            lineStyle: { color: '#00ff88', width: 2 },
            areaStyle: {
              color: {
                type: 'linear', x: 0, y: 0, x2: 0, y2: 1,
                colorStops: [
                  { offset: 0, color: 'rgba(0, 255, 136, 0.3)' },
                  { offset: 1, color: 'rgba(0, 255, 136, 0.05)' }
                ]
              }
            }
          },
          {
            name: 'Z轴',
            type: 'line',
            data: filteredData.valueData.z || [],
            smooth: 0.3,
            symbol: 'none',
            lineStyle: { color: '#ffaa00', width: 2 },
            areaStyle: {
              color: {
                type: 'linear', x: 0, y: 0, x2: 0, y2: 1,
                colorStops: [
                  { offset: 0, color: 'rgba(255, 170, 0, 0.3)' },
                  { offset: 1, color: 'rgba(255, 170, 0, 0.05)' }
                ]
              }
            }
          }
        ]
      };
    },


    /**
     * 获取空的显示数据
     */
    getEmptyDisplayData() {
      const timeData = Array(60).fill('').map((_, index) => {
        const time = new Date(Date.now() - (59 - index) * 4000); // 改为4秒间隔
        return time.toLocaleTimeString('zh-CN', {
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        });
      });

      return {
        timeData,
        valueData: {
          x: Array(60).fill(0),
          y: Array(60).fill(0),
          z: Array(60).fill(0)
        }
      };
    },



    handleResize() {
      if (this.accelerationChart) {
        // 延迟调整大小，确保容器尺寸已更新
        setTimeout(() => {
          this.accelerationChart.resize();
          console.log('📊 图表大小已调整');
        }, 100);
      }
    },

    /**
     * 动态计算图表边距
     */
    calculateGridMargins(valueData) {
      // 计算Y轴数值的最大值，用于动态调整左边距
      let maxValue = 0;
      if (valueData && valueData.x && valueData.y && valueData.z) {
        const allValues = [...valueData.x, ...valueData.y, ...valueData.z];
        maxValue = Math.max(...allValues.filter(v => v !== null && v !== undefined));
      }

      // 根据最大值动态调整左边距
      let leftMargin = '3%';
      if (maxValue >= 1000) {
        leftMargin = '12%'; // 四位数需要更多空间
      } else if (maxValue >= 100) {
        leftMargin = '10%'; // 三位数需要中等空间
      }

      return {
        left: leftMargin,
        right: '2%', // 减少右边距，充分利用空间
        bottom: '18%', // 增加底部边距，为完整时间格式留出空间
        top: '15%',
        containLabel: true
      };
    },

    /**
     * 动态计算X轴标签间隔（适应10分钟完整时间范围，充分利用空间）
     */
    calculateXAxisInterval(timeDataLength) {
      // 目标：在可用空间内显示20个标签，提供更详细的时间信息
      if (timeDataLength <= 60) {
        return 3; // 60个点，每3个显示一个（显示20个标签，3秒间隔）
      } else if (timeDataLength <= 120) {
        return 6; // 120个点，每6个显示一个（显示20个标签，6秒间隔）
      } else if (timeDataLength <= 300) {
        return 15; // 300个点，每15个显示一个（显示20个标签，约15秒间隔）
      } else if (timeDataLength <= 600) {
        return 30; // 600个点，每30个显示一个（显示20个标签，约30秒间隔）
      } else {
        // 超过600个点，确保显示大约20个标签
        return Math.max(Math.ceil(timeDataLength / 20), 5);
      }
    },

    /**
     * 智能计算X轴标签间隔，基于时间数据的实际差异
     */
    calculateSmartXAxisInterval(timeData) {
      if (!timeData || timeData.length <= 1) {
        return 1;
      }

      // 分析时间数据的重复情况
      const uniqueLabels = new Set(timeData);
      const uniqueRatio = uniqueLabels.size / timeData.length;

      // 如果重复率很高，增加间隔，但仍尽量显示更多标签
      if (uniqueRatio < 0.3) {
        return Math.ceil(timeData.length / 15); // 显示15个标签
      } else if (uniqueRatio < 0.6) {
        return Math.ceil(timeData.length / 18); // 显示18个标签
      } else {
        return this.calculateXAxisInterval(timeData.length); // 使用默认策略（20个标签）
      }
    },

    /**
     * 计算稳定的Y轴范围（带缓存机制）
     */
    calculateStableYAxisRange(valueData) {
      if (!valueData || !valueData.x || !valueData.y || !valueData.z) {
        return this.cachedYAxisRange;
      }

      // 收集所有有效数值
      const allValues = [
        ...valueData.x.filter(v => v !== null && v !== undefined && !isNaN(v)),
        ...valueData.y.filter(v => v !== null && v !== undefined && !isNaN(v)),
        ...valueData.z.filter(v => v !== null && v !== undefined && !isNaN(v))
      ];

      if (allValues.length === 0) {
        return this.cachedYAxisRange;
      }

      const dataMin = Math.min(...allValues);
      const dataMax = Math.max(...allValues);

      // 计算新的稳定范围
      let stableMin = 0; // 始终从0开始，贴紧底部
      let stableMax;

      if (dataMax <= 5) {
        stableMax = 5;
      } else if (dataMax <= 10) {
        stableMax = 10;
      } else if (dataMax <= 20) {
        stableMax = 20;
      } else if (dataMax <= 50) {
        stableMax = 50;
      } else if (dataMax <= 100) {
        stableMax = 100;
      } else {
        // 对于更大的值，向上取整到最近的50的倍数，但要贴紧数据
        const margin = (dataMax - dataMin) * 0.02; // 只留2%的上边距，更贴紧
        stableMax = Math.ceil((dataMax + margin) / 50) * 50;
      }

      const newRange = { min: stableMin, max: stableMax };

      // 只有当新范围与缓存范围差异较大时才更新
      const currentTime = Date.now();
      const shouldUpdate =
        !this.lastYAxisRangeUpdate ||
        (currentTime - this.lastYAxisRangeUpdate) > this.yAxisRangeUpdateThreshold ||
        Math.abs(newRange.max - this.cachedYAxisRange.max) > this.cachedYAxisRange.max * 0.3; // 变化超过30%才更新

      if (shouldUpdate) {
        this.cachedYAxisRange = newRange;
        this.lastYAxisRangeUpdate = currentTime;
        console.log('📊 Y轴范围已更新:', newRange);
      }

      return this.cachedYAxisRange;
    },

    /**
     * 过滤有效的时间数据
     */
    filterValidTimeData(timeData, valueData) {
      const validIndices = [];

      // 找出所有有效的数据点索引
      for (let i = 0; i < timeData.length; i++) {
        const time = timeData[i];
        const hasValidTime = time && time !== '' && time !== null && time !== undefined;
        const hasValidData = (valueData.x && valueData.x[i] !== null && valueData.x[i] !== undefined) ||
                           (valueData.y && valueData.y[i] !== null && valueData.y[i] !== undefined) ||
                           (valueData.z && valueData.z[i] !== null && valueData.z[i] !== undefined);

        if (hasValidTime && hasValidData) {
          validIndices.push(i);
        }
      }

      // 构建过滤后的数据
      const filteredTimeData = validIndices.map(i => timeData[i]);
      const filteredValueData = {
        x: validIndices.map(i => valueData.x ? valueData.x[i] : 0),
        y: validIndices.map(i => valueData.y ? valueData.y[i] : 0),
        z: validIndices.map(i => valueData.z ? valueData.z[i] : 0)
      };

      console.log(`📊 数据过滤: ${timeData.length} -> ${filteredTimeData.length} 个有效数据点`);

      return {
        timeData: filteredTimeData,
        valueData: filteredValueData
      };
    },

    /**
     * 计算Y轴刻度间隔
     */
    calculateYAxisInterval(min, max) {
      const range = max - min;

      if (range <= 5) {
        return 1; // 0, 1, 2, 3, 4, 5
      } else if (range <= 10) {
        return 2; // 0, 2, 4, 6, 8, 10
      } else if (range <= 20) {
        return 4; // 0, 4, 8, 12, 16, 20
      } else if (range <= 50) {
        return 10; // 0, 10, 20, 30, 40, 50
      } else if (range <= 100) {
        return 20; // 0, 20, 40, 60, 80, 100
      } else {
        return Math.ceil(range / 5); // 确保有大约5个刻度
      }
    },

    /**
     * 计算Y轴分割数量
     */
    calculateYAxisSplitNumber(min, max) {
      const range = max - min;
      const interval = this.calculateYAxisInterval(min, max);
      return Math.ceil(range / interval);
    },

    handleWebSocketDataUpdate(data) {
      if (!data || !data.deviceId || data.deviceId !== this.currentDevice.id) {
        return;
      }

      console.log('📊 AccelerationChart: 收到WebSocket数据更新');
      this.scheduleChartUpdate();
    },

    /**
     * 处理图表数据管理器的更新事件
     */
    handleChartDataUpdate(deviceIds) {
      if (!Array.isArray(deviceIds) || !deviceIds.includes(this.currentDevice.id)) {
        return;
      }

      console.log('📊 AccelerationChart: 收到数据管理器更新');
      this.scheduleChartUpdate();
    },

    /**
     * 调度图表更新（使用requestAnimationFrame优化）
     */
    scheduleChartUpdate() {
      if (this.updateAnimationId) {
        cancelAnimationFrame(this.updateAnimationId);
      }

      this.updateAnimationId = requestAnimationFrame(() => {
        this.updateChart();
        this.updateAnimationId = null;
      });
    },

    /**
     * 更新图表
     */
    updateChart() {
      if (!this.accelerationChart || this.accelerationChart.isDisposed()) {
        console.log('📊 图表未初始化，重新初始化');
        this.initAccelerationChart();
        return;
      }

      try {
        const option = this.getAccelerationChartOption();

        // 使用平滑更新，避免轴线晃动
        this.accelerationChart.setOption(option, {
          notMerge: false,    // 不完全替换，只更新变化的部分
          lazyUpdate: false,  // 立即更新
          silent: true        // 静默更新，减少动画闪烁
        });

        console.log('📈 图表平滑更新完成');
      } catch (error) {
        console.error('❌ 图表更新失败:', error);
        this.initAccelerationChart();
      }
    },

    /**
     * 使用实时数据更新图表
     */
    updateChartWithRealTimeData() {
      if (!this.accelerationChart || this.accelerationChart.isDisposed()) {
        console.log('📊 图表未初始化，重新初始化');
        this.initAccelerationChart();
        return;
      }

      try {
        const option = this.getAccelerationChartOption();

        // 使用平滑动画更新图表
        this.accelerationChart.setOption(option, {
          notMerge: false,
          lazyUpdate: false,
          silent: false
        });

        console.log('📈 图表实时更新完成');
      } catch (error) {
        console.error('❌ 图表实时更新失败:', error);
        // 如果更新失败，重新初始化图表
        this.initAccelerationChart();
      }
    },

    /**
     * 更新设备加速度数据
     * @param {Object} data 新的加速度数据
     */
    updateDeviceAccelerationData(data) {
      // 通过emit通知父组件更新数据
      this.$emit('acceleration-data-updated', {
        deviceId: data.deviceId,
        data: data.data
      });
    },

    /**
     * 使用新数据更新图表
     * @param {Object} data 新的加速度数据
     */
    updateChartWithNewData(data) {
      if (!this.accelerationChart || !data.data) {
        return;
      }

      try {
        // 获取新的图表配置
        const newOption = this.getAccelerationChartOptionFromWebSocketData(data.data);

        // 使用平滑动画更新图表
        this.accelerationChart.setOption(newOption, {
          notMerge: false,
          lazyUpdate: false,
          silent: false
        });

        console.log('Chart updated with WebSocket data');
      } catch (error) {
        console.error('Error updating chart with WebSocket data:', error);
      }
    },

    /**
     * 从WebSocket数据生成图表配置
     * @param {Object} data WebSocket数据
     * @returns {Object} ECharts配置对象
     */
    getAccelerationChartOptionFromWebSocketData(data) {
      if (!data) {
        return this.getAccelerationChartOption();
      }

      const currentData = this.accelerationType === 'rms' ? data.rms : data.peak;
      const timeData = data.timeData || this.generateTimeData();

      return {
        animation: true,
        animationDuration: this.animationDuration,
        animationEasing: 'cubicOut',
        xAxis: {
          data: timeData
        },
        series: [
          {
            name: 'X轴',
            data: currentData.x || [],
            animationDelay: 0
          },
          {
            name: 'Y轴',
            data: currentData.y || [],
            animationDelay: 100
          },
          {
            name: 'Z轴',
            data: currentData.z || [],
            animationDelay: 200
          }
        ]
      };
    },

    /**
     * 处理滑动窗口数据更新
     * @param {Object} data 滑动窗口数据
     */
    handleWindowDataUpdate(data) {
      if (!data || !data.deviceId) {
        return;
      }

      // 检查是否是当前设备的数据
      if (data.deviceId === this.currentDevice.id) {
        console.log('📈 AccelerationChart: 收到滑动窗口数据更新:', data.deviceId);

        // 使用滑动窗口的数据更新图表
        if (data.data) {
          this.updateChartWithWindowData(data.data);
          console.log('📊 AccelerationChart: 使用滑动窗口数据更新图表完成');
        } else {
          // 如果滑动窗口数据为空，回退到直接刷新图表
          this.$nextTick(() => {
            if (this.hasDeviceData(this.currentDevice.id)) {
              this.initAccelerationChart();
              console.log('📈 AccelerationChart: 回退到直接刷新图表');
            }
          });
        }

        // 更新最后更新时间
        this.lastUpdateTime = data.timestamp || Date.now();
      }
    },

    /**
     * 使用滑动窗口数据更新图表
     * @param {Object} windowData 滑动窗口数据
     */
    updateChartWithWindowData(windowData) {
      if (!this.accelerationChart || !windowData) {
        return;
      }

      try {
        const currentData = this.accelerationType === 'rms' ? windowData.rms : windowData.peak;
        const timeData = windowData.timeData || this.generateTimeData();

        const option = {
          animation: true,
          animationDuration: this.animationDuration,
          animationEasing: 'cubicOut',
          xAxis: {
            data: timeData
          },
          series: [
            {
              name: 'X轴',
              data: currentData.x || [],
              animationDelay: 0
            },
            {
              name: 'Y轴',
              data: currentData.y || [],
              animationDelay: 100
            },
            {
              name: 'Z轴',
              data: currentData.z || [],
              animationDelay: 200
            }
          ]
        };

        // 使用平滑动画更新图表
        this.accelerationChart.setOption(option, {
          notMerge: false,
          lazyUpdate: false,
          silent: false
        });

        console.log('📊 图表已使用滑动窗口数据更新');
      } catch (error) {
        console.error('使用滑动窗口数据更新图表失败:', error);
      }
    },

    /**
     * 生成默认时间数据
     * @returns {Array} 时间数组
     */
    generateTimeData() {
      const now = Date.now();
      return Array(60).fill(null).map((_, index) => {
        const time = new Date(now - (59 - index) * 4000); // 改为4秒间隔
        return time.toLocaleTimeString('zh-CN', {
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        });
      });
    },

    /**
     * 格式化时间，包含毫秒信息以避免重复
     */
    formatTimeWithMilliseconds(date) {
      const time = date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });

      // 如果需要更高精度，可以添加毫秒
      const milliseconds = date.getMilliseconds();
      if (milliseconds > 0) {
        return `${time}.${milliseconds.toString().padStart(3, '0')}`;
      }

      return time;
    },

    /**
     * 智能去重时间标签，确保相邻标签不重复（不使用括号）
     */
    deduplicateTimeLabels(timeData) {
      if (!timeData || timeData.length === 0) {
        return [];
      }

      const result = [];
      const usedLabels = new Set();

      for (let i = 0; i < timeData.length; i++) {
        let currentLabel = timeData[i];

        // 如果当前标签已经使用过，跳过这个数据点
        // 这样可以避免重复标签，而不是添加括号
        if (!usedLabels.has(currentLabel)) {
          result.push(currentLabel);
          usedLabels.add(currentLabel);
        }
      }

      return result;
    }
  }
}
</script>

<style lang="scss" scoped>
.acceleration-chart {
  width: 100%;
  height: 100%;
  background: rgba(3, 12, 49, 0.6);
  border: 1px solid rgba(28, 89, 156, 0.3);
  border-radius: 10px;
  display: flex;
  flex-direction: column;

  .chart-title {
    height: 40px;
    padding: 0 20px;
    font-size: 17px;
    color: #fff;
    display: flex;
    align-items: center;
    position: relative;
    justify-content: space-between;

    .title-left {
      display: flex;
      align-items: center;
      gap: 10px;

      .status-indicator {
        padding: 2px 8px;
        border-radius: 4px;
        font-size: 12px;
        color: #fff;

        &.normal {
          background: #20b84e;
        }

        &.warning {
          background: #ff2b2b;
        }

        &.waiting {
          background: #ffb300;
        }

        &.offline {
          background: #808080;
        }
      }
    }

    .title-right {
      display: flex;
      align-items: center;
      gap: 15px;

      .acceleration-type-selector {
        display: flex;
        gap: 5px;

        .type-btn {
          padding: 2px 8px;
          border: 1px solid rgba(255, 255, 255, 0.3);
          border-radius: 4px;
          background: transparent;
          color: rgba(255, 255, 255, 0.6);
          cursor: pointer;
          font-size: 12px;
          transition: all 0.3s ease;

          &:hover {
            border-color: #fff;
            color: #fff;
          }

          &.active {
            background: rgba(255, 255, 255, 0.1);
            border-color: #fff;
            color: #fff;
          }
        }
      }

      .position-dropdown {
        .el-dropdown-link {
          padding: 4px 12px;
          border: 1px solid rgba(28, 89, 156, 0.4);
          border-radius: 6px;
          background: rgba(3, 12, 49, 0.6);
          color: rgba(255, 255, 255, 0.7);
          cursor: pointer;
          font-size: 12px;
          transition: all 0.3s ease;
          display: inline-flex;
          align-items: center;
          min-width: 90px;
          justify-content: space-between;
          backdrop-filter: blur(5px);
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);

          &:hover {
            border-color: rgba(28, 89, 156, 0.8);
            background: rgba(28, 89, 156, 0.2);
            color: #fff;
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4);
          }

          i {
            margin-left: 6px;
            font-size: 10px;
            transition: transform 0.3s ease;
          }

          &:hover i {
            transform: rotate(180deg);
          }
        }
      }

      .ai-btn {
        padding: 4px 12px;
        border: 1px solid rgba(255, 43, 43, 0.6);
        border-radius: 4px;
        background: rgba(255, 43, 43, 0.1);
        color: #ff2b2b;
        cursor: pointer;
        font-size: 12px;
        transition: all 0.3s ease;
        animation: aiPulse 1.2s infinite ease-in-out;

        &:hover {
          background: rgba(255, 43, 43, 0.2);
          border-color: #ff2b2b;
        }

        i {
          margin-right: 4px;
        }
      }
    }
  }

  #accelerationChart {
    flex: 1;
    min-height: 200px;
    width: 100% !important;
    height: 100% !important;
  }

  .chart-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0; // 允许flex子项收缩
    position: relative; // 为遮罩提供定位基准
  }
}

// 状态遮罩样式
.status-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(3, 12, 49, 0.85);
  backdrop-filter: blur(8px);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 10;
  border-radius: 8px;

  .mask-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    padding: 40px;
    max-width: 400px;

    .status-icon {
      margin-bottom: 20px;

      i {
        font-size: 64px;
        color: #ff6b6b;

        &.el-icon-success {
          color: #52c41a;
        }
        &.el-icon-warning {
          color: #ff4d4f;
        }
        &.el-icon-time {
          color: #faad14;
        }
        &.el-icon-error {
          color: #8c8c8c;
        }
      }
    }

    .status-text {
      h3 {
        color: #fff;
        font-size: 20px;
        font-weight: 600;
        margin: 0 0 12px 0;
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
      }

      p {
        color: #8f9bb3;
        font-size: 14px;
        margin: 0;
        line-height: 1.5;
      }
    }
  }
}

.no-data-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  font-size: 16px;
  color: #8f9bb3;
}

.no-data-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;

  i {
    font-size: 48px;
    margin-bottom: 10px;
  }
}

@keyframes aiPulse {
  0%, 100% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.7;
    transform: scale(1.05);
  }
}

// 下拉菜单样式覆盖
::v-deep .el-dropdown-menu {
  background: rgba(3, 12, 49, 0.95) !important;
  border: 1px solid rgba(28, 89, 156, 0.5) !important;
  border-radius: 6px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.6) !important;
  backdrop-filter: blur(10px);

  .el-dropdown-menu__item {
    background: transparent !important;
    color: rgba(255, 255, 255, 0.7) !important;
    font-size: 12px;
    padding: 8px 16px;
    transition: all 0.3s ease;
    border-bottom: 1px solid rgba(255, 255, 255, 0.05);

    &:last-child {
      border-bottom: none;
    }

    &:hover {
      background: rgba(28, 89, 156, 0.3) !important;
      color: #fff !important;
      transform: translateX(2px);
    }

    &:focus {
      background: rgba(28, 89, 156, 0.3) !important;
      color: #fff !important;
    }

    &.is-active {
      background: rgba(28, 89, 156, 0.4) !important;
      color: #fff !important;
      position: relative;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        width: 3px;
        background: linear-gradient(to bottom, #1890ff, #40a9ff);
      }
    }
  }
}

// 全局下拉菜单样式强制覆盖 - 使用更强的选择器
::v-deep .el-popper {
  .el-dropdown-menu {
    background: rgba(3, 12, 49, 0.95) !important;
    border: 1px solid rgba(28, 89, 156, 0.5) !important;
    border-radius: 6px !important;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.6) !important;

    .el-dropdown-menu__item {
      background: transparent !important;
      color: rgba(255, 255, 255, 0.7) !important;

      &:hover, &:focus {
        background: rgba(28, 89, 156, 0.3) !important;
        color: #fff !important;
      }

      &.is-active {
        background: rgba(28, 89, 156, 0.4) !important;
        color: #fff !important;
      }
    }
  }
}
</style>

<style>
/* 全局下拉菜单样式覆盖 - 不使用scoped */
.el-dropdown-menu {
  background: rgba(3, 12, 49, 0.95) !important;
  border: 1px solid rgba(28, 89, 156, 0.5) !important;
  border-radius: 6px !important;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.6) !important;
  backdrop-filter: blur(10px) !important;
}

.el-dropdown-menu .el-dropdown-menu__item {
  background: transparent !important;
  color: rgba(255, 255, 255, 0.7) !important;
  font-size: 12px !important;
  padding: 8px 16px !important;
  transition: all 0.3s ease !important;
  border-bottom: 1px solid rgba(255, 255, 255, 0.05) !important;
}

.el-dropdown-menu .el-dropdown-menu__item:last-child {
  border-bottom: none !important;
}

.el-dropdown-menu .el-dropdown-menu__item:hover,
.el-dropdown-menu .el-dropdown-menu__item:focus {
  background: rgba(28, 89, 156, 0.3) !important;
  color: #fff !important;
  transform: translateX(2px) !important;
}

.el-dropdown-menu .el-dropdown-menu__item.is-active {
  background: rgba(28, 89, 156, 0.4) !important;
  color: #fff !important;
  position: relative !important;
}

.el-dropdown-menu .el-dropdown-menu__item.is-active::before {
  content: '' !important;
  position: absolute !important;
  left: 0 !important;
  top: 0 !important;
  bottom: 0 !important;
  width: 3px !important;
  background: linear-gradient(to bottom, #1890ff, #40a9ff) !important;
}
</style>
